<?php
/**
 * CourseModel.class.php
 * 课程模型
 * 
 * @author 	王中艺	<wangzy_smile@qq.com>
 * @date 	2017-02-24
 */
namespace Admin\Model;

class CourseModel extends BaseModel {

	//重定义数据表名
	protected 	$trueTableName = 't_course';

	/**
	 * 获取课程列表
	 * @param   $timeS 开始时间
	 * @param   $timeE 结束时间
	 * @param   $page 页码数
	 * @param   $pageHtml 页面html
	 * @return  $list
	 */
	function getList($timeS, $timeE, $page, &$pageHtml){
		$where 	= 'a.status != -1';
		if($timeS)
			$where 	.= ' and a.create_time >= '.$timeS;
		if($timeE)
			$where 	.= ' and a.create_time <= '.$timeE;

		$list 	= $this->table('t_course a')
			->where($where)
			->join('left join t_teacher b on a.teacher_id = b.id')
			->order('id desc')
			->field('a.id, a.name, a.banner, a.decipt, a.price, a.score, a.buy_type, a.create_time, 
				a.status, a.cate,a.chapter, a.buy_count, a.main_title, a.sub_title, 
				b.name teacher_name, b.id teacher_id')
			->page($page, C('PAGE_COUNT'))
			->select();

		$list 	= $this->_analyField('course', $list, true);

		if($pageHtml === true){
			$count 	= $this->cache(true)->count();
			$Page 	= new \Think\Page($count, C('PAGE_COUNT'));
			$pageHtml 	= $Page->angular_show();
		}
			
		return $list;
	}

	/**
	 * 添加课程
	 * @param   $courseInfo 课程信息
	 * @return  $coruseInfo 课程信息
	 */
	function addCourse($courseInfo){
		$courseInfo['create_time']	= time();
		$courseInfo['update_time']	= time();
		$courseId 	= $this->add($courseInfo);
		if($courseId === false){
			$this->errMsg 	= '课程添加失败!(t_course)';
			return false;
		}
		$courseInfo['id']	= $courseId;
		return $courseInfo;
	}

	/**
	 * 更改课程
	 * @param   $courseId 课程ID
	 * @param   $courseInfo 课程信息
	 * @return  $boolean
	 */
	function changeCourse($courseId, $courseInfo){
		$courseInfo['update_time']	= time();
		$ret 	= $this->where('id = %d', $courseId)->save($courseInfo);
		if($ret === false){
			$this->errMsg 	= '课程保存失败!';
			return false;
		}
		S('xinletu_course_info_'.$courseId, null);
		return true;
	}

	/**
	 * 课程详情获取
	 * @param   $courseId 课程ID
	 * @return  $courseInfo
	 */
	function detailCourse($courseId){
		$courseInfo 	= $this->table('t_course a')
			->join('left t_teacher b on a.teacher_id = b.id')
			->cache('xinletu_course_info_'.$courseId)
			->field('a.id, a.name, a.main_title, a.sub_title, a.banner, a.decipt, a.teacher_id, a.chapter, 
				a.price, a.score, a.buy_type, a.create_time, a.play_type, a.buy_type, a.tag, a.status,
				b.name teacher_name')
			->find();

		return $courseInfo;
	}

	/**
	 * 获取章节信息
	 * @param   $courseId 课程ID
	 * @return  $list
	 */
	function getChapterList($courseId){
		$list 	= M('t_course_chapter', null)
			->where('course_id = %d and status = 1', $courseId)
			->order('id')
			->select();

		$index 	= 0;
		foreach($list as &$item){
			$index 	+= 1;
			$item['index']	= $index;
			$item['sim_name'] 	= msubstr($item['name'], 0, 10);
			$item['sim_decipt']	= msubstr($item['decipt'], 0, 10);
			$item['imgs']	= (array)json_decode($item['imgs'], true);
			$item['img_count']	= count($item['imgs']);
			// $item['attach']	= json_encode($item['attach'], true);
			$item['try_text']	= $item['is_try'] == 1 ? '是' : '否';
		}
		return $list;
	}

	/**
	 * 添加章节
	 * @param   $chapterInfo 章节信息
	 * @return  $chapterId
	 */
	function addChapter($chapterInfo){
		$chapterId 	= M('t_course_chapter', null)->add($chapterInfo);
		if($chapterId === false){
			$this->errMsg 	= '章节添加失败!';
			return false;
		}

		//课程章节数目添加
		M('t_course', null)->where('id = %d', $chapterInfo['course_id'])->setInc('chapter');
		return $chapterId;
	}

	/**
	 * 变更章节
	 * @param   $chapterId 章节ID
	 * @param   $chapterInfo 章节信息
	 * @return  $chapterInfo [<description>]
	 */
	function changeChapter($chapterId, $chapterInfo){
		$ret 	= M('t_course_chapter', null)
			->where('id = %d', $chapterId)
			->save($chapterInfo);
		if($ret === false){
			$this->errMsg 	= '章节变更失败!';
			return false;
		}
		$chapterInfo['id']	= $chapterId;
		return $chapterInfo;
	}

	/**
	 * 销售记录
	 * @param   $getType 获取方式
	 * @param   $page 页码数
	 * @param   $keyword 关键词 [课程|用户]:[nickname]
	 * @return  list
	 */
	function sellLog($page = 1, $keyword, $getType, $timeS, $timeE, &$pageHtml){
		$where 	= '1 = 1';
		if(strpos($keyword, ':')){
			$keyword 	= explode(':', $keyword);
			switch($keyword[0]){
				case '课程':
					$where 	.= sprintf(' and c.name like "%%%s%%"', $keyword[1]);
				break;
				case '用户':
					$where 	.= sprintf(' and b.nickname like "%%%s%%"', $keyword[1]);
				break;
			}
		}
		if($getType)$where 	.= sprintf(' and a.get_type = %d', $getType);
		if($timeS)	$where 	.= sprintf(' and a.create_time >= %d', $timeS);
		if($timeE)	$where 	.= sprintf(' and a.create_time <= %d', $timeE);
		$list 	= $this->table('t_user_course a')
			->join('left join t_user b on a.user_id = b.id')
			->join('left join t_course c on a.course_id = c.id')
			->where($where)
			->page($page, C('PAGE_COUNT'))
			->order('id desc')
			->field('a.id, a.user_id, a.course_id, b.nickname, c.name course_name, a.get_type, 
				a.get_relate_id, a.status, a.price, a.create_time')
			->cache(true)
			->select();
		foreach($list as &$item){
			$item['create_date']	= date('Y-m-d', $item['create_time']);
			$item['sim_course_name']	= msubstr($item['course_name'], 0, 10);
			$item['get_type_text']	= C('COURSE_GET_TEXT.'.$item['get_type']);
			$item['status_text']	= C('USER_COURSE_STATUS.'.$item['status']);
		}

		$count 	= $this->table('t_user_course a')
			->join('left join t_user b on a.user_id = b.id')
			->join('left join t_course c on a.course_id = c.id')
			->where($where)
			->cache(true)
			->count();
		$Page 	= new \Think\Page($count, C('PAGE_COUNT'));
		$pageHtml 	= $Page->angular_show();
		return $list;
	}

	/**
	 * 获取课程交易列表
	 * @param 	$dataType 	数据类型 1：单笔购买；2：购物车购买
	 * @param   $page 页码数
	 * @param   $keyword 关键词
	 * @param   $timeS 起始时间
	 * @param   $timeE 结束时间
	 * @param   &$pageHtml 引用页面HTML分页元素
	 * @param 	&$total 	合计信息
	 * @return  $list [<description>]
	 */
	function getBargainList($dataType, $keyword, $timeS, $timeE, $page, &$pageHtml, &$total){
		$where 	= '1 = 1';
		if($keyword){
			$keyword 	= explode(':', $keyword);
			if(count($keyword) == 1){
				$where 	.= sprintf(' and (b.nickname like "%%s%%" or b.id = "%s")', $keyword[0], $keyword[0]);
			}
			if(count($keyword) == 2){
				switch($keyword[0]){
					case '用户':
						$where 	.= sprintf(' and (b.nickname like "%%%s%%" or b.id = "%s")', $keyword[1], $keyword[1]);
					break;
					case '课程':
						$where 	.= sprintf(' and (d.name like "%%%s%%" or d.id = "%s")', $keyword[1], $keyword[1]);
					break;
				}
			}
			
		}
		if($timeS)
			$where 	.= sprintf(' and a.create_time >= %d', $timeS);
		if($timeE)
			$where 	.= sprintf(' and a.create_time <= %d', $timeE);

		//单笔购买记录
		if($dataType == 1){
			$where 	.= ' and a.get_type = 1';
			$list 	= M('t_user_course a', null)
				->join('left join t_user b on a.user_id = b.id')
				->join('left join t_money c on a.get_relate_id = c.id')
				->join('left join t_course d on a.course_id = d.id')
				->where($where)
				->order('a.id desc')
				->page($page, C('PAGE_COUNT'))
				// ->cache(true)
				->field('a.id, a.user_id, d.name course_name, a.create_time, a.price, c.amount, c.trade_no,
					b.nickname, b.truename, c.deduct, c.id money_id, a.get_type, a.get_relate_id')
				->select();
			foreach($list as &$item){
				$item['create_date']	= date('Y-m-d', $item['create_time']);
				$item['profit']	= $item['amount'] - $item['deduct'];
			}

			if($pageHtml){
				$count 	= M('t_user_course a', null)
					->join('left join t_user b on a.user_id = b.id')
					->join('left join t_course d on a.course_id = d.id')
					->where($where)
					->cache(true)
					->count();
				$Page 	= new \Think\Page($count, C('PAGE_COUNT'));
				$pageHtml 	= $Page->angular_show();
			}

			if($total){
				$total 	= M('t_user_course a', null)
					->join('left join t_user b on a.user_id = b.id')
					->join('left join t_money c on a.get_relate_id = c.id')
					->join('left join t_course d on a.course_id = d.id')
					->where($where)
					->field('count(a.id) count, sum(c.amount) amount, sum(c.deduct) deduct')
					->cache(true)
					->find();
				$total['profit'] 	= $total['amount'] - $total['deduct'];
			}

			return $list;
		}

		//购物车购买
		if($dataType == 2){
			$where 	.= ' and a.get_type = 3';
			$list 	= M('t_user_course a', null)
				->join('left join t_user b on a.user_id = b.id')
				->join('left join t_shop_cart e on a.get_relate_id = e.id')
				->join('left join t_money c on e.money_id = c.id')
				->join('left join t_course d on a.course_id = d.id')
				->where($where)
				->order('a.id desc')
				->page($page, C('PAGE_COUNT'))
				->cache(true)
				->field('a.id, a.user_id, a.course_id, d.name course_name, a.create_time, a.price, c.amount, c.trade_no,
					b.nickname, b.truename, c.deduct, c.id money_id, a.get_type, a.get_relate_id,
					e.goods_infos, c.code_id')
				->select();

			foreach($list as &$item){
				$item['create_date']	= date('Y-m-d', $item['create_time']);
				//单笔课程分成计算
				if($item['goods_infos']){
					$goodsInfos 	= json_decode($item['goods_infos'], true);
					$_total 	= 0;
					$_now 	= 0;
					foreach($goodsInfos as $goodsInfo){
						$_total 	+= $goodsInfo['price'];
						if($goodsInfo['id'] == $item['course_id'])
							$_now 	= $goodsInfo['price'];
					}
					$weight 	= round($_now/$_total, 4);
					$item['amount'] 	= round($item['amount'] * $weight, 2);
					$item['deduct'] 	= round($item['deduct'] * $weight, 2);
				}
				$item['profit']	= $item['amount'] - $item['deduct'];
			}

			if($pageHtml){
				$count 	= M('t_user_course a', null)
					->join('left join t_user b on a.user_id = b.id')
					->join('left join t_course d on a.course_id = d.id')
					->where($where)
					->cache(true)
					->count();
				$Page 	= new \Think\Page($count, C('PAGE_COUNT'));
				$pageHtml 	= $Page->angular_show();
			}

			if($total){
				$total 	= M('t_user_course a', null)
					->join('left join t_user b on a.user_id = b.id')
					->join('left join t_shop_cart e on a.get_relate_id = e.id')
					->join('left join t_money c on e.money_id = c.id')
					->join('left join t_course d on a.course_id = d.id')
					->where($where)
					->field('count(a.id) count, sum(c.amount) amount, sum(c.deduct) deduct')
					->cache(true)
					->find();
				$total['profit'] 	= $total['amount'] - $total['deduct'];
			}

			return $list;
		}
	}

	/**
	 * 导出Excel
	 * @param   $start 	开始位置
	 * @param   $lenght 到处长度
	 * @param   $keyword 关键词
	 * @param   $timeS 起始时间
	 * @param   $timeE 结束时间
	 * @return  list [<description>]
	 */
	function outBargainExcel($start, $length, $keyword, $timeS, $timeE){
		$where 	= 'a.get_type = 1';
		if($keyword)
			$where 	.= sprintf(' and b.nickname like "%s%%"', $keyword);
		if($timeS)
			$where 	.= sprintf(' and a.create_time >= %d', $timeS);
		if($timeE)
			$where 	.= sprintf(' and a.create_time <= %d', $timeE);

		if($start === false){
			$count 	= M('t_user_course a', null)
				->join('left join t_user b on a.user_id = b.id')
				->where($where)
				->cache(true)
				->count();
			return $count;
		}

		$list 	= M('t_user_course a', null)
			->join('left join t_user b on a.user_id = b.id')
			->join('left join t_money c on a.get_relate_id = c.id')
			->join('left join t_course d on a.course_id = d.id')
			->join('left join t_coupon_code e on c.code_id = e.id')
			->where($where)
			->order('a.id desc')
			->page($page, $length)
			->cache(true)
			->field('a.id, a.user_id, d.name course_name, a.create_time, a.price, c.amount, c.trade_no,
				b.nickname, b.truename, b.role_id, c.deduct, c.id money_id, a.get_type, a.get_relate_id,
				e.code, e.amount code_amount')
			->select();

		$roleMap 	= \Common\Model\UserModel::ROLE_MAP;
		foreach($list as &$item){
			$item['create_date']	= date('Y-m-d', $item['create_time']);
			$item['profit']	= $item['amount'] - $item['deduct'];
			$item['role_text']	= $roleMap[$item['role_id']];
		}

		return $list;	
	}

}